<template>
  <div class="docx-preview">
    <el-scrollbar class="docx-container">
      <!-- 加载状态 -->
      <div v-show="loading" class="loading-container">
        <el-icon class="is-loading" :size="50">
          <Loading />
        </el-icon>
        <p>Word 文档加载中...</p>
      </div>

      <!-- 错误状态 -->
      <div v-show="error && !loading" class="error-container">
        <el-icon :size="80">
          <WarningFilled />
        </el-icon>
        <p>{{ error }}</p>
      </div>

      <!-- 文档内容容器 - 始终渲染，只是隐藏 -->
      <div 
        ref="docxContainer" 
        class="docx-content"
        v-show="!loading && !error"
      ></div>
    </el-scrollbar>
  </div>
</template>

<script setup>
import { ref, watch, nextTick } from 'vue'
import { renderAsync } from 'docx-preview'
import { Loading, WarningFilled } from '@element-plus/icons-vue'

const props = defineProps({
  file: {
    type: Object,
    required: true
  }
})

const docxContainer = ref(null)
const loading = ref(false)
const error = ref('')

// 加载 Word 文档
const loadDocx = async () => {
  try {
    // 重置状态
    error.value = ''
    loading.value = true
    
    // 等待 DOM 更新
    await nextTick()
    
    // 再次确认容器存在（现在应该存在了，因为用的是 v-show）
    if (!docxContainer.value) {
      console.error('docxContainer 仍未找到，等待更长时间...')
      // 多等待几次
      await new Promise(resolve => setTimeout(resolve, 50))
      await nextTick()
      
      if (!docxContainer.value) {
        throw new Error('DOM 容器初始化失败')
      }
    }

    // 清空容器
    docxContainer.value.innerHTML = ''
    console.log('✓ 容器就绪，开始读取文件:', props.file.name)

    // 获取文件 ArrayBuffer
    let arrayBuffer
    
    if (props.file.isUrl) {
      console.log('✓ 使用 URL 加载 Word:', props.file.url)
      const response = await fetch(props.file.url)
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }
      arrayBuffer = await response.arrayBuffer()
    } else {
      console.log('✓ 使用本地文件加载 Word')
      arrayBuffer = await props.file.raw.arrayBuffer()
    }
    
    console.log('✓ 文件读取成功，大小:', arrayBuffer.byteLength)
    
    // 渲染 Word 文档
    console.log('✓ 开始渲染 Word 文档...')
    await renderAsync(arrayBuffer, docxContainer.value, undefined, {
      className: 'docx-wrapper',
      inWrapper: true,
      ignoreWidth: false,
      ignoreHeight: false,
      renderHeaders: true,
      renderFooters: true,
      renderFootnotes: true,
      renderEndnotes: true,
      useBase64URL: true,
      trimXmlDeclaration: true,
      experimental: false
    })
    
    console.log('✓ Word 文档渲染成功！')
    loading.value = false
  } catch (err) {
    console.error('✗ Word 文档加载失败:', err)
    if (err.message.includes('CORS') || err.message.includes('Failed to fetch')) {
      error.value = 'Word 加载失败：CORS 跨域限制。建议：1) 下载后上传 2) 使用代理 URL'
    } else {
      error.value = `Word 文档加载失败: ${err.message || '请确保文件格式正确'}`
    }
    loading.value = false
  }
}

watch(() => props.file, (newFile) => {
  if (newFile) {
    console.log('📄 检测到新文件，准备加载:', newFile.name)
    loadDocx()
  }
}, { immediate: true })
</script>

<style scoped>
.docx-preview {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.docx-container {
  flex: 1;
  overflow: auto;
}

.docx-content {
  padding: 40px;
  background: #ffffff;
  margin: 20px auto;
  max-width: 900px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  min-height: calc(100% - 40px);
}

.loading-container,
.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #409EFF;
}

.error-container {
  color: #F56C6C;
}

.loading-container p,
.error-container p {
  margin-top: 16px;
  font-size: 14px;
}

/* Word 文档样式 */
:deep(.docx-wrapper) {
  background: white;
  padding: 30px;
  min-height: 500px;
}

:deep(.docx-wrapper section.docx) {
  margin-bottom: 20px;
  padding: 0;
}

:deep(.docx-wrapper p) {
  margin: 8px 0;
  line-height: 1.8;
}

:deep(.docx-wrapper table) {
  border-collapse: collapse;
  width: 100%;
  margin: 16px 0;
}

:deep(.docx-wrapper table td),
:deep(.docx-wrapper table th) {
  border: 1px solid #ddd;
  padding: 8px;
}

/* docx-preview 库所需的基础样式 */
:deep(.docx) {
  background: white;
  color: black;
  font-family: 'Calibri', 'Arial', sans-serif;
  font-size: 11pt;
}

:deep(.docx section) {
  page-break-after: always;
}

:deep(.docx h1) {
  font-size: 2em;
  font-weight: bold;
  margin: 0.67em 0;
}

:deep(.docx h2) {
  font-size: 1.5em;
  font-weight: bold;
  margin: 0.75em 0;
}

:deep(.docx h3) {
  font-size: 1.17em;
  font-weight: bold;
  margin: 0.83em 0;
}

:deep(.docx img) {
  max-width: 100%;
  height: auto;
}
</style>

